package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"sync"
	"time"
	"traning/grpc_stream/proto"
)

func main() {
	UnaryClientInterceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		start := time.Now()
		err := invoker(ctx, method, req, reply, cc, opts...)
		fmt.Printf("request use time %s", time.Since(start))
		return err
	}
	opts := make([]grpc.DialOption, 0)
	opts = append(opts, grpc.WithInsecure())
	opts = append(opts, grpc.WithUnaryInterceptor(UnaryClientInterceptor))
	conn, _ := grpc.Dial("localhost:50052", opts...)
	defer conn.Close()

	// 服务端流模式
	c := proto.NewGreeterClient(conn)
	res, _ := c.GetStream(context.Background(),&proto.StreamReqData{Data: "ice"})
	for {
		a,err := res.Recv()
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(a)
	}

	//	客户端流模式
	puStr, _ := c.PullStream(context.Background())
	i := 0
	for {
		_ = puStr.Send(&proto.StreamReqData{Data: fmt.Sprintf("ice %d", i)})
		i ++
		if i > 3 {
			break
		}
	}
	time.Sleep(time.Second)

    // 双向模式
    AllStr , _ := c.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			res, _ := AllStr.Recv()
			fmt.Printf("AllStream recive %v \n" , res)
		}
	}()

	go func() {
		defer wg.Done()
		for {
			AllStr.Send(&proto.StreamReqData{Data: fmt.Sprintf("我是客户端\n")})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()
    
    time.Sleep(time.Second * 2)
}



